package com.mission.schedule.CommonDialog;

import android.app.Dialog;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.mission.schedule.R;
import com.mission.schedule.applcation.App;
import com.mission.schedule.clock.QueryAlarmData;
import com.mission.schedule.entity.ScheduleTable;
import com.mission.schedule.utils.ListViewForScrollView;
import com.mission.schedule.utils.XmlUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 日程铃声选择对话框
 * Created by liwei on 2017/4/18.
 */

public class CalenderRingDialog extends Dialog {


    CallBack callBack;

    private ListViewForScrollView lingsheng_lv, lingsheng_lv1;
    Context context;
    WindowManager windowManager;
    List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    LingShengAdapter adapter, adapter1;
    private String alarmSound;
    private String alarmSoundDesc;

    String schID = "", repeadId = "";

    public CalenderRingDialog(@NonNull final Context context, @StyleRes int themeResId, WindowManager windowManager, final String schIDs, final String repeadIds) {
        super(context, themeResId);
        this.context = context;
        this.windowManager = windowManager;

        setCanceledOnTouchOutside(true);

        View view = LayoutInflater.from(context).inflate(R.layout.dialog_lingsheng, null);
        setContentView(view);
        this.schID = schIDs;
        this.repeadId = repeadIds;

        list = XmlUtil.readBellXML(context);
        lingsheng_lv = (ListViewForScrollView) view.findViewById(R.id.lingsheng_lv);
        lingsheng_lv1 = (ListViewForScrollView) view.findViewById(R.id.lingsheng_lv1);
        adapter1 = new LingShengAdapter(context, list.subList(0, 2));
        adapter = new LingShengAdapter(context, list.subList(2, list.size()));

        lingsheng_lv.setAdapter(adapter);
        lingsheng_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Map<String, String> mMap = (Map<String, String>) lingsheng_lv.getAdapter().getItem(position);
                if (!schIDs.isEmpty() && !repeadIds.isEmpty()) {
                    if (!schID.isEmpty()) {
                        App.getDBcApplication().updateSceduleDataLingsheng(Integer.parseInt(schID), mMap.get("name"), mMap.get("value"));
                        if (!repeadId.equals("0") && !repeadId.equals("") && repeadId != null) {
                            App.getDBcApplication().updateSchuledRepeatTo(schID);
                        }
                        QueryAlarmData.writeAlarm(context);
                    }
                }

                callBack.reminderEditTime(mMap.get("name"), mMap.get("value"));
                dismiss();

            }
        });
        lingsheng_lv1.setAdapter(adapter1);
        lingsheng_lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Map<String, String> mMap = (Map<String, String>) lingsheng_lv1.getAdapter().getItem(position);
                if (!schIDs.isEmpty() && !repeadIds.isEmpty()) {
                    if (!schID.isEmpty()) {
                        App.getDBcApplication().updateSceduleDataLingsheng(Integer.parseInt(schID), mMap.get("name"), mMap.get("value"));
                        if (!repeadId.equals("0") && !repeadId.equals("") && repeadId != null) {
                            App.getDBcApplication().updateSchuledRepeatTo(schID);
                        }
                        QueryAlarmData.writeAlarm(context);
                    }
                }

                callBack.reminderEditTime(mMap.get("name"), mMap.get("value"));
                dismiss();

            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        WindowManager.LayoutParams params = window.getAttributes();
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        params.width = windowManager.getDefaultDisplay().getWidth();
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
    }

    public interface CallBack {
        void reminderEditTime(String lingshengname, String code);
    }

    public CallBack getCallBack() {
        return callBack;
    }

    public void setCallBack(CallBack callBack) {
        this.callBack = callBack;
    }

    public class LingShengAdapter extends BaseAdapter {
        private Context context;
        private List<Map<String, String>> mList;

        public LingShengAdapter(Context context,
                                List<Map<String, String>> mList) {
            this.context = context;
            this.mList = mList;
        }

        @Override
        public int getCount() {
            return mList == null ? 0 : mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {

            View view = convertView;
            LingShengAdapter.ViewWapper viewWapper = null;
            if (view == null) {
                view = LayoutInflater.from(context).inflate(
                        R.layout.adapter_lingsheng, null);
                viewWapper = new LingShengAdapter.ViewWapper(view);
                view.setTag(viewWapper);
            } else {
                viewWapper = (LingShengAdapter.ViewWapper) view.getTag();
            }
            TextView lingsheng_name_tv = viewWapper.getLingShengName();
            TextView shiting_tv = viewWapper.getShiTing();
            lingsheng_name_tv.setText(mList.get(position).get("name").toString());
            int position1 = position;
            if (position == list.size() - 1) {
                shiting_tv.setText("");
            } else {
                shiting_tv.setText("试听");
                shiting_tv.setTextColor(context.getResources().getColor(R.color.gongkai_txt));
            }
            shiting_tv.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    alarmSound = mList.get(position).get("value") + ".mp3".replace("\\n", "");
                    alarmSoundDesc = mList.get(position).get("name");

                    if(mediaPlayer != null) {
                        mediaPlayer.stop();
                        try {
                            mediaPlayer.reset();
                            AssetFileDescriptor fileDescriptor = context.getAssets().openFd(alarmSound);
                            mediaPlayer.setDataSource(
                                    fileDescriptor.getFileDescriptor(),
                                    fileDescriptor.getStartOffset(),
                                    fileDescriptor.getLength());
                            mediaPlayer.prepare();
                            mediaPlayer.seekTo(0);
                            mediaPlayer.start();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        playMusic();
                    }
                }
            });

            return view;
        }

        class ViewWapper {
            private View view;
            private TextView lingsheng_name_tv;
            private TextView shiting_tv;
            private View state_item_line;

            private ViewWapper(View view) {
                this.view = view;
            }

            private TextView getLingShengName() {
                if (lingsheng_name_tv == null) {
                    lingsheng_name_tv = (TextView) view
                            .findViewById(R.id.lingsheng_name_tv);
                }
                return lingsheng_name_tv;
            }

            private TextView getShiTing() {
                if (shiting_tv == null) {
                    shiting_tv = (TextView) view.findViewById(R.id.shiting_tv);
                }
                return shiting_tv;
            }

            private View getStateViewLine() {
                if (state_item_line == null) {
                    state_item_line = view.findViewById(R.id.state_item_line);
                }
                return state_item_line;
            }
        }
    }


    MediaPlayer mediaPlayer = new MediaPlayer();
    private void playMusic() {

        try {
            AssetFileDescriptor fileDescriptor = context.getAssets().openFd(alarmSound);
            mediaPlayer.setDataSource(
                    fileDescriptor.getFileDescriptor(),
                    fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
